var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');

var manager = require('./routes/manager');
var wxshop = require('./routes/wxshop');
var delivery = require('./routes/delivery');

var redisconf = require('./conf/config')['redis']['default'];

var session = require('express-session');
var RedisStore = require('connect-redis')(session);

var multer = require('multer')

var upload = multer({ dest: '/tmp/file' })

var app = express();

//session中间件
var sessionMiddleware = session({
    name:'sesskey',
    store: new RedisStore(redisconf),
    resave:true,
    saveUninitialized:true,
    secret: 'bzsudio',
    key: 'fn',
    cookie:{
        //     天* 小时*分钟*秒*毫秒
        maxAge: 1* 1  *60  *60*1000}
});
app.use(sessionMiddleware);

app.use(cookieParser('bzsudio'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.post('/fileUpload',upload.single('file'),function (req, res, next) {
    // req.file is the `avatar` file
    // req.body will hold the text fields, if there were any
    console.log(req.file);
    console.log(req.body);
    var file = req.file;
    var fileFormat = (file.originalname).split(".");
    var fileName = req.body.userId + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1];
    fs.renameSync(file.path,'/home/img/'+fileName)

    res.status(200).end(JSON.stringify({code:"0",msg:"添加成功",data:fileName}));
});

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.text({type: 'text/xml'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

app.use('/manager', manager);
app.use('/wxshop', wxshop);
app.use('/deli', delivery);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  res.render('404');
  // next(err);
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = err;
    console.log(err.message)

    // render the error page
    res.status(err.status || 500);
    res.render('500');
});

module.exports = app;
